package org.lzy.shop.database.entity

import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import org.lzy.shop.response.GoodsSpecResponse

@Entity(
    tableName = "goods_specs",
    foreignKeys = [
        ForeignKey(
            entity = CartItemEntity::class,
            parentColumns = ["id"],
            childColumns = ["cartItemId"],
            onDelete = ForeignKey.CASCADE
        )
    ],
    indices = [Index("cartItemId")] // 为外键添加索引以提高性能
)
data class GoodsSpecEntity(
    @PrimaryKey(autoGenerate = true)
    val id: Int = 0,
    val goodsId: Int,
    val name: String?,
    val price: String?,
    val stock: String?,
    val sortNum: String?,
    val images: MutableList<String?>?,
    val cartItemId: Int // 外键，关联购物车项
) {
    companion object {
        fun fromGoodsSpecResponse(spec: GoodsSpecResponse, cartItemId: Int): GoodsSpecEntity {
            return GoodsSpecEntity(
                goodsId = spec.goodsId,
                name = spec.name,
                price = spec.price,
                stock = spec.stock,
                sortNum = spec.sortNum,
                images = spec.images,
                cartItemId = cartItemId
            )
        }
    }

    fun toGoodsSpecResponse(): GoodsSpecResponse {
        return GoodsSpecResponse(
            id = this.id,  // 修正为使用实体类自己的id
            goodsId = this.goodsId,
            name = this.name,
            price = this.price,
            stock = this.stock,
            sortNum = this.sortNum,
            images = this.images
        )
    }
}